<?php

namespace app\zyhsapi\controller\v1;

use app\common\lib\Aes;
use app\common\lib\Alidayu;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsAppleidUser;
use app\zyhsapi\model\ZyhsConfig;
use app\zyhsapi\model\ZyhsLoginLog;
use app\zyhsapi\model\ZyhsQq;
use app\zyhsapi\model\ZyhsRecode;
use app\zyhsapi\model\ZyhsSmsLog;
use app\zyhsapi\model\ZyhsTelLogin;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserCoupon;
use app\zyhsapi\model\ZyhsWechat;
use app\zyhsapi\model\ZyhsWeibo;
use app\zyhsapi\service\CacheZyhs;
use app\zyhsmarketing\service\MarketingCallback;
use Exception;
use GuzzleHttp\Exception\GuzzleException;
use think\Db;
use think\Log;
use think\response\Json;

class Login extends ZyhsAuth
{
    protected $loginType = null;
    protected $msg = '';

    /**
     * 三方登录接口
     * @return Json
     * @throws ApiException
     * @throws GuzzleException
     */
    public function OuterLogin()
    {
        $param = input('param.param');
        $param = $param ? json_decode($param, true) : [];
        $type = input('param.type/d');
        $this->loginType = $type;
        switch ($type)
        {
            // 微信登录
            case 1:
                if ($this->headers['app-type'] === 'ios')
                {
                    $wechat_user = $param;
                } else
                {
                    $wechat_user = (new ZyhsWechat())->WechatInfo($param);
                }
                $res = $this->wechat($wechat_user);
                break;
            // QQ登录
            case  2:
                $res = $this->qq($param);
                break;
            // 微博登录
            case  3:
                $res = $this->weibo($param);
                break;
            // AppleID登录
            case  5:
                $res = $this->appleId($param);
                break;
            default:

                return show(config('code.error'), '未知的登录方式');
        }

        if ($this->msg)
        {
            return show(config('code.error'), $this->msg);
        }

        //记录登录
        $this->LoginLog($res['id'], $type);
        #删除字段
        unset($res['temporary_tel']);

        return show(config('code.success'), '登录成功', $res);
    }

    /**
     * 微信登录
     * @param $wechat_user json 微信用户信息
     * @return array
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    private function wechat($wechat_user)
    {
        $this->msg = '';
        $wechat_user['headimgurl'] = $wechat_user['headimgurl'] ?? '';
        $wechat_user['sex'] = $wechat_user['sex'] ?? ($wechat_user['gender'] ?? 0);

        $WechatModel = new ZyhsWechat();
        //验证是否注册过
        $User = $WechatModel->getWechatInfo($wechat_user['unionid']);
        if ($User)
        {
            return $this->LoginUser($User, $wechat_user);
        }
        //新增用户，qq和user表进行数据添加，检测冷却时间
        $checkResult = Util::ZyhsRegistCheckLogoutCD(['unionid' => $wechat_user['unionid']]);
        if (!$checkResult['result'])
        {
            return $this->msg = $checkResult['msg'];
        }

        Db::startTrans();
        try
        {
            $res = $this->RegUser($wechat_user, 1, $wechat_user['unionid']);

            $uid = $res['id'];
            $wechat_insert = [
                'uid' => $uid,
                'nickname' => $wechat_user['nickname'] ?? '匿名用户',
                'sex' => $wechat_user['sex'] ?? 2,// 微信注册用户 性别字段可能不存在
                'city' => $wechat_user['city'] ?? '',
                'province' => $wechat_user['province'] ?? '',
                'country' => $wechat_user['country'] ?? '',
                'headimgurl' => $wechat_user['headimgurl'] ?? '',
                'openid' => $wechat_user['openid'],
                'unionid' => $wechat_user['unionid'],
                'create_time' => $this->request->time(),
                'update_time' => $this->request->time(),
            ];
            //qq表生成数据
            $WechatModel->SaveData($wechat_insert);

            Db::commit();
        }
        catch (Exception $e)
        {
            Log::write('用户注册失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            Db::rollback();
            $this->msg = '用户注册失败';
            return [];
        }

        return $res;
    }

    /**
     * QQ登录
     * @param $param
     * @return array|Json
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    private function qq($param)
    {
        $this->msg = '';
        $QqModel = new ZyhsQq();
        // 获取用户qq信息
        $qq_user = $QqModel->QqInfo($param);
        // 验证是否注册过
        $User = $QqModel->getUserQqInfoFromCache($qq_user['unionid']);
        if ($User)
        {
            return $this->LoginUser($User, $qq_user);
        }
        // 新增用户，qq和user表进行数据添加
        $checkResult = Util::ZyhsRegistCheckLogoutCD(['qq_unionid' => $qq_user['unionid']]);
        if (!$checkResult['result'])
        {
            return $this->msg = $checkResult['msg'];
        }
        Db::startTrans();
        try
        {
            $res = $this->RegUser($qq_user, 2, $qq_user['unionid']);
            $qq_insert = [
                'uid' => $res['id'],
                'openid' => $param['openid'],
                'unionid' => $qq_user['unionid'],
                'create_time' => time(),
                'nickname' => $qq_user['nickname'],
                'sex' => $qq_user['sex'],
                'avatar' => $qq_user['figureurl_qq_1'],
            ];
            //qq表生成数据
            $QqModel->SaveData($qq_insert);
            Db::commit();
        }
        catch (Exception $e)
        {
            Log::write('用户注册失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            Db::rollback();
            return $this->msg = '用户注册失败';
        }
        return $res;
    }

    /**
     * 微博登录
     * @param $param
     * @return array|Json
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    private function weibo($param)
    {
        $this->msg = '';
        $WbModel = new ZyhsWeibo();
        // 获取用户weibo信息
        $wb_user = $WbModel->WeiboInfo($param);
        // 验证是否注册过
        $User = $WbModel->getUserWbInfoFromCache($param['uid']);
        if ($User)
        {
            return $this->LoginUser($User, $wb_user);
        }

        $checkResult = Util::ZyhsRegistCheckLogoutCD(['wuid' => $param['uid']]);
        if (!$checkResult['result'])
        {
            return $this->msg = $checkResult['msg'];
        }
        Db::startTrans();
        try
        {
            // 新增用户，qq和user表进行数据添加
            $res = $this->RegUser($wb_user, 3);
            $wb_insert = [
                'uid' => $res['id'],
                'wbuid' => $param['uid'],
                'create_time' => time(),
                'nickname' => $wb_user['name'],
                'sex' => $wb_user['sex'],
                'avatar' => $wb_user['profile_image_url'],
            ];
            //wb表生成数据
            $WbModel->SaveData($wb_insert);
            Db::commit();
        }
        catch (Exception $e)
        {
            Log::write('用户注册失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            Db::rollback();
            return $this->msg = '用户注册失败';
        }
        return $res;
    }

    /**
     * AppleId登录
     * @param $param
     * @return array|Json
     * @throws ApiException
     * @throws GuzzleException
     */
    public function appleId($param)
    {
        $this->msg = '';
        $dbModel = new ZyhsAppleidUser();
        if (!isset($param['apple_id']) || empty($param['apple_id']))
        {
            return $this->msg = '用户登陆失败';
        }
        $param['unionid'] = $param['apple_id'];
        $param['headimgurl'] = $param['avatar'] ?? '';
        $param['nickname'] = $param['name'] ?? '';
        $param['nickname'] = $param['nickname'] ?: '准' . uniqid();
        $param['sex'] = 0;

        // 验证是否注册过
        $user = $dbModel->getUserInfo($param['apple_id']);
        if ($user)
        {   // 去登陆
            $res = $this->LoginUser($user, $param);
        } else
        {
            // 去注册
            //新增用户，qq和user表进行数据添加
            $checkResult = Util::ZyhsRegistCheckLogoutCD(['apple_id' => $param['apple_id']]);
            if (!$checkResult['result'])
            {
                return $this->msg = $checkResult['msg'];
            }

            try
            {
                Db::startTrans();
                $res = $this->RegUser($param, 5, $param['apple_id']);
                $param['uid'] = $res['id'];
                $param['create_time'] = $this->request->time();
                $dbModel->SaveData($param);
                Db::commit();
            }
            catch (Exception $e)
            {
                Log::write($param['apple_id'] . '：苹果用户注册失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
                Db::rollback();
                return $this->msg = '用户注册失败';
            }
        }
        return $res;
    }

    /**
     * 用户注册
     * @param $user_info
     * @param $type 1微信 2QQ 3微博
     * @param string $code 身份标识
     * @return array
     * @throws ApiException
     * @throws GuzzleException
     * @throws Exception
     */
    private function RegUser($user_info, $type, $code = '')
    {
        $this->msg = '';
        $time = $this->request->time();

        $ip = $this->request->ip();
        Db::startTrans();
        try
        {
            $token_info = $this->getUserTokenInfo($user_info);
            // headimgurl可能不存在，此处进行初始化
            $user_info['headimgurl'] = $user_info['headimgurl'] ?? '';
            // sex可能不存在，此处进行初始化
            $user_info['sex'] = $user_info['sex'] ?? 0;

            if ($user_info['headimgurl'])
            {
                $avatarInfo = Util::wxImgUploadOss($user_info['headimgurl'], 'uploads/avatar');
            } else
            {
                $avatarInfo = [
                    'success' => true,
                    'url' => '',
                ];
            }

            if ($avatarInfo['success'] == false)
            {
                Log::write('上传三方头像失败:' . $avatarInfo['message'], 'error');
            }

            $avatar = $avatarInfo['success'] ? $avatarInfo['url'] : $user_info['headimgurl'];

            $user = [
                'uen' => substr(md5(microtime() . random_int(0, 1000000) . uniqid('', false)), 0, 12),
                'nickname' => $user_info['nickname'],
                'avatar' => $avatar,
                'sex' => $user_info['sex'],
                'reg_time' => $time,
                'reg_ip' => $ip,
                'last_login' => $time,
                'last_ip' => $ip,
                'last_active' => $time,
                'is_first_login' => 1,// 首次登陆标记
                'token' => $token_info['token'],
                'token_expire' => $token_info['token_expire'],
                'email' => null,
                'forbidden' => 0,
                'has_self_recode' => 0,
                'uc_id' => uuid($user_info['unionid'] . microtime()),
                'channel' => Util::getChannelId(),
            ];
            $user['id'] = (new ZyhsUser())->insertGetId($user);
            (new ZyhsUserCoupon())->regUserSendBenefits($user['id']);
            Db::commit();
        }
        catch (Exception $e)
        {
            Log::write($type . '用户注册失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            Db::rollback();
            return $this->msg = '用户注册失败';
        }

        if (!Util::IsIos())
        {   // 安卓手机  回传打点
            $oaid = $this->headers['oaid'] ?? '';
            $mobileType = input('mobile_type/d', 0);
            (new MarketingCallback())->uploadActiveData($oaid, (int)$user['id'], 2, $mobileType);
        }

        return [
            'id' => (int)$user['id'],
            'self_rid' => 0,
            'user_access_token' => (new Aes())->encryptWithOpenssl($token_info['token'] . '||' . $user['id'], 'zyhsapp'),
            'has_bind_tel' => 0, // 是否绑定了手机号 1绑定了 0未绑定
            'is_register' => 1,
            'uen' => $user['uen'],
            'tel' => '',
        ];
    }

    /**
     * 用户登录
     * @param $user
     * @param $user_info
     * @return array|Json
     * @throws GuzzleException
     * @throws ApiException
     */
    private function LoginUser($user, $user_info)
    {
        $this->msg = '';
        if (!isset($user['forbidden']) || $user['forbidden'] == 1)
        {
            return show(config('code.error'), '该账号禁止登录');
        }
        $UserModel = new ZyhsUser();
        try
        {
            $uid = (int)$user['uid'];
            $token_info = $this->getUserTokenInfo($user_info);

            if (empty($user['avatar']) || preg_match('/^http(s?):\/\/*/', $user['avatar']))
            {
                $avatarInfo = Util::wxImgUploadOss($user_info['headimgurl'], 'uploads/avatar');
                if ($avatarInfo['success'])
                {
                    $token_info['avatar'] = $avatarInfo['url'];
                    // 更新档案信息
                    $recordModel = new ZyhsRecode();
                    $rid = $recordModel->where('uid', $uid)->where('isself', 1)->value('id');
                    $recordModel->UpdateData($uid, $rid, ['avatar' => $avatarInfo['url']]);
                }
            }

            $UserModel->save($token_info, ['id' => $uid]);
        }
        catch (Exception $e)
        {
            Log::write('用户登录失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            return $this->msg = '用户登录失败';
        }
        $userInfo = $UserModel->getInfoById($uid);
        $coinTel = config('zyhsapp.coin_mobile');
        //准币测试号
        if (isset($coinTel[$userInfo['tel']]) && $coinTel[$userInfo['tel']] === 2)
        {
            return show(config('code.error'), '该账号禁止登录');
        }
        //检测用户准了号
        $UserModel->check_uen($userInfo);
        $UserModel->removeUserCache($uid);
        return [
            'id' => $uid,
            'self_rid' => $userInfo['rid'],
            'user_access_token' => (new Aes())->encryptWithOpenssl($token_info['token'] . '||' . $uid, 'zyhsapp'),
            'has_bind_tel' => ($userInfo['tel'] ?? '') ? 1 : 0,
            'is_register' => 0,
            'uen' => $userInfo['uen'],
            'tel' => $userInfo['tel'],
        ];
    }

    /**
     * 获取用户token信息
     * @param $user_info
     * @return array
     */
    private function getUserTokenInfo($user_info)
    {
        // 生成token  和 token到期时间
        $token = IAuth::setAppLoginToken($user_info['unionid']);
        $data = [
            'token' => $token,
            'token_expire' => strtotime('+' . config('zyhsapp.login_time_out_day') . ' days'),
        ];
        return $data;
    }

    /**
     * 记录用户的登陆日志
     * @param $uid
     * @param $type 1=>微信，2=>qq,3=>微博 4=>手机号
     * @return bool
     */
    private function LoginLog($uid, $type)
    {
        $time = $this->request->time();
        $ip = $this->request->ip();
        // 记录登陆日志  改成异步操作
        $insert = [
            'uid' => $uid,
            'login_time' => $time,
            'login_type' => $type,
            'login_ip' => $ip,
        ];
        try
        {
            (new ZyhsLoginLog())->SaveData($insert);
        }
        catch (Exception $e)
        {
            Log::write('记录用户登录失败：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error');
            return false;
        }

        return true;
    }

    /**
     * 获取手机验证码
     * @return Json
     * @throws \Exception
     */
    public function getCode()
    {
        $type = input('type/d', 0);
        $tel = input('tel/s', '');// 账号注销时，手机号为空
        $time = input('time/d', 0);
        $sign = trim(input('sign/s', ''));
        $headers = $this->request->header();
        if (isset($headers['app-type']) && in_array($headers['app-type'], ['ios', 'android'], true))
        {
            $tel = (new Aes())->decryptWithOpenssl($tel, 'zyhsapp');
        } else if (isset($headers['app-type']) && in_array($headers['app-type'], ['flutter-web', 'flutter-mac', 'flutter-win', 'flutter-linux'], true))
        {
            if (md5($tel . $time . 'b0Rrpe5cuSONdDEz') !== $sign)
            {
                Log::write('手机号验签错误：tel=' . $tel . ',time=' . $time . 'sign=' . $sign, 'error', true);
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        }

        $areaCode = input('area_code/d', 86);

        // 1=>登录，2=>绑定，3=>注销
        switch ($type)
        {
            case 1:
                $codeType = 'login';
                // 检查手机号是否正确
                if (!$tel || !Util::telRuleCheck($tel, $areaCode))
                {
                    return show(config('code.error'), '手机号错误');
                }
                /**
                 * 过滤非法获取验证码请求，直接返回发送成功
                 */
                if (Util::isIllegalRequest(true))
                {
                    return show(config('code.success'), '发送成功');
                }
                try
                {
                    $user = (new ZyhsUser())->where(['tel' => $tel])->findOrFail();
                }
                catch (\think\Exception $e)
                {
                    $user = [];
                }
                break;
            case 2:
                $codeType = 'bind';
                // 检验手机号是否注册过，未注册过通过
                if (!$tel || !Util::telRuleCheck($tel, $areaCode))
                {
                    return show(config('code.error'), '手机号错误');
                }
//                try
//                {
//                    $user = (new ZyhsUser)->where(['tel' => $tel])->findOrFail();
//                }
//                catch (Exception $e)
//                {
//                    $user = [];
//                }
//                if ($user)
//                {
//                    return show(config('code.error'), '此手机号已注册，请使用此手机号登录或注销此手机号重新绑定');
//                }
                break;
            case 3:
                $codeType = 'logout';
                // 服务器获取手机号，若有则通过
                if (!$this->user)
                {
                    return show(config('code.denied'), '登录失效');
                }

                if ($this->user['tel'])
                {
                    $telData = explode('-', $this->user['tel']);
                    if (count($telData) > 1)
                    {
                        [$areaCode, $tel] = $telData;
                    } else
                    {
                        $areaCode = 86;
                        $tel = $this->user['tel'];
                    }
                } else
                {
                    return show(config('code.error'), '您未绑定手机号');
                }
                break;
            default:
                return show(config('code.error'), '未知的登录方式');
                break;
        }

        $telStr = 'isSend:' . $areaCode . '-' . $tel;
        $isSendCode = CacheZyhs::get($telStr);
        if ($isSendCode)
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }

        $time = time();// 当前时间  有效时间暂定为十分钟 600s
        $expire = 600;
        $ip = $this->request->ip();
        try
        {
            $data = (new ZyhsTelLogin())->where(['tel' => $tel, 'expire_time' => ['>', $time]])->findOrFail()->toArray();
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        // 十分钟内无已有验证码
        if (empty($data))
        {
            $code = random_int(100000, 999999);// 六位验证码

            $expire_time = $time + $expire;
            try
            {
                Db::table('good_wechat.zyhs_tel_login')->insertGetId([
                    'tel' => "$tel",
                    'create_time' => $time,
                    'expire_time' => $expire_time,
                    'code' => $code,
                ]);
            }
            catch (\Exception $e)
            {
                Log::write('获取手机验证码失败：' . $e->getMessage() . PHP_EOL . '失败行数：' . $e->getLine() . PHP_EOL . '错误文件：【' . $e->getFile() . '】');
                return show(config('code.error'), '发送失败');
            }

        } else
        {
            $code = $data['code'];
        }
        $alidayu = (new ZyhsConfig())->configInfo('alidayu');
        // 短信模板ID 配置KEY
        if ($type === 3)
        {// 注销
            $smsIdConfigKey = $areaCode === 86 ? 'logout_code' : 'abroad_logout_code';
        } else
        {// 登录或绑定
            $smsIdConfigKey = $areaCode === 86 ? 'login_code' : 'abroad_login_code';
        }
        $result = Alidayu::getInstance()->sendSmsZyhs($tel, $code, $alidayu[$smsIdConfigKey], $areaCode, $codeType);
        if (!$result)
        {
            return show(config('code.error'), '发送失败');
        }
        CacheZyhs::set($telStr, 1, 50);
        // 记录短信日志
        (new ZyhsSmsLog())->save([
            'tel' => "$tel",
            'ip' => $ip,
            'create_time' => $time,
            'type' => $type,
        ]);

        return show(config('code.success'), '发送成功');
    }

    /**
     * @title 手机验证码登录
     * @method POST
     * @return Json
     * @throws ApiException
     */
    public function mobile()
    {
        $tel = input('tel/s', '');
        $time = input('time/d', 0);
        $sign = trim(input('sign/s', ''));

        $headers = $this->request->header();
        if (isset($headers['app-type']) && in_array($headers['app-type'], ['ios', 'android'], true))
        {
            $tel = (new Aes())->decryptWithOpenssl($tel, 'zyhsapp');
        } else if (isset($headers['app-type']) && in_array($headers['app-type'], ['flutter-web', 'flutter-mac', 'flutter-win', 'flutter-linux'], true))
        {
            if (md5($tel . $time . 'b0Rrpe5cuSONdDEz') !== $sign)
            {
                Log::write('手机号验签错误：tel=' . $tel . ',time=' . $time . 'sign=' . $sign, 'error', true);
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
        }

        $code = input('code/s', '');
        $areaCode = input('area_code/d', 86);
        $time = $this->request->time();
        $ip = $this->request->ip();
        $appConfig = config('zyhsapp');
        $mobileTel = $areaCode === 86 ? $tel : $areaCode . '-' . $tel;
        //准币测试号
        if (isset($appConfig['coin_mobile'][$tel]) && $appConfig['coin_mobile'][$tel] === 2)
        {
            return show(config('code.error'), '该账号禁止登录');
        }
        // 手机号不可注册
        $user = $this->CheckUserTel($tel, $areaCode);
        // 短信验证码 或 密码是否存在
        if (empty($code))
        {
            return show(config('code.error'), '手机短信验证码');
        }
        // 短信登录时，检测验证码是否正确
        if (!empty($code))
        {
            if (!in_array($tel, $appConfig['mobile'])
                || ($areaCode === 86 && $code != substr($appConfig['code'] * (substr($tel, 3, 6)), 0, 6)))
            {
                //苹果和安卓应用商店审核账号，固定验证码为666666
                if (($tel == '13045794520' && $code == '666666')
                    || ($tel == '13261877781' && $code == '666666'))
                {

                } else
                {   //  validate 严格校验
                    $mobileCode = Alidayu::getInstance()->checkSmsIdentifyZyhs($tel, $areaCode, 'login');

                    if ($code != $mobileCode)
                    {
                        return show(config('code.error'), '短信验证码错误');
                    }
                }
            }
        }
        // 生成token  和 token到期时间
        $token = IAuth::setAppLoginToken($tel);
        $data = [
            'token' => $token,
            'token_expire' => strtotime("+" . $appConfig['login_time_out_day'] . " days"),
        ];
        $UserModel = new ZyhsUser();
        //判断用户是否绑定准了号
        if ($user)
        {
            $UserModel->check_uen($user);
        }
        $nickname = preg_replace('/^([\w-]{3})([\w]*)([0-9]{4}$)/i', '$1****$3', $tel);
        $isRegister = false;
        // 该用户是否正常  forbidden==1 禁止登录
        if ($user && $user['forbidden'] == 0)
        {
            // 已过期重新生成access_token
            if ($time > $user['token_expire'] || !in_array($tel, $appConfig['mobile']))
            {
                $UserModel->save($data, ['tel' => $mobileTel]);
            } else
            {
                $token = $user['token'];
            }
            if (!$user['nickname'])
            {
                try
                {
                    $UserModel->where('tel', $tel)->update(['nickname' => $nickname]);
                }
                catch (\think\Exception $e)
                {
                    Log::write('手机验证码登陆时初始化用户昵称失败' . $e->getMessage(), true);
                }
            }
        } elseif ($user && $user['forbidden'] == 1)
        {
            return show(config('code.error'), '该账号禁止登录');
        } //手机号不可注册
        elseif (!$user && !empty($code) && !empty($tel))
        {
            $isRegister = true;
            $checkResult = Util::ZyhsRegistCheckLogoutCD(['tel' => $tel]);
            if (!$checkResult['result'])
            {
                throw new ApiException($checkResult['msg'], 200, config('code.error'));
            }
            // 第一次登录 注册数据
            $user['uen'] = substr(md5($this->request->time(true) . mt_rand(0, 1000000) . uniqid()), 0, 12);
            $user['nickname'] = $nickname;
            $user['reg_time'] = $time;
            $user['reg_ip'] = $ip;
            $user['last_login'] = $time;
            $user['last_ip'] = $ip;
            $user['last_active'] = $time;
            $user['status'] = 1;
            $user['sex'] = 1;
            $user['tel'] = $mobileTel; // 国内手机号不拼接国际手机区号
            $user['is_first_login'] = 1;
            $user['uc_id'] = uuid($tel . microtime());
            $user['token'] = $data['token'];
            $user['token_expire'] = $data['token_expire'];
            $user['has_self_recode'] = 0;
            $user['channel'] = Util::getChannelId();
            try
            {
                $user['id'] = $UserModel->insertGetId($user);
                (new ZyhsUserCoupon())->regUserSendBenefits($user['id']);
            }
            catch (\Exception $e)
            {
                return show(config('code.error'), '注册失败,请稍后重试');
            }
        }

        if ($user)
        {
            $id = (int)($user['id']);
            if ($isRegister)
            {
                // 绑定成功 查看手机号是否
                $syncRecodeInfo = (new ZyhsRecode())->getAccountRecodeNumByTelZyhs($mobileTel, $id);
                if (!Util::IsIos()) //  安卓 打点回传
                {   // 回传打点
                    $oaid = $this->headers['oaid'] ?? '';
                    $mobileType = input('mobile_type/d', 0);
                    (new MarketingCallback())->uploadActiveData($oaid, $id, 2, $mobileType);
                }
            }
            // 获取自己档案ID
            $recordInfo = (new ZyhsRecode())->getRecodeLists($id, 1);
            $result = [
                'id' => $id,
                'self_rid' => $recordInfo ? (int)($recordInfo['id'] ?? 0) : 0,
                'user_access_token' => (new Aes())->encryptWithOpenssl($token . "||" . $user['id'], 'zyhsapp'),
                'has_bind_tel' => 1,     // 是否绑定了手机号 1绑定了 0未绑定
                'sync_recode_info' => $syncRecodeInfo ?? [],
                'is_register' => $isRegister ? 1 : 0,
                'uen' => $user['uen'],
                'tel' => $tel,
            ];
            // 记录登陆日志
            $this->LoginLog($id, 4);

            $UserModel->removeUserCache($id);

            return show(config('code.success'), 'ok', $result);
        }

        return show(config('code.error'), '登录失败');
    }

    /**
     * @title 绑定手机号失败后快捷登录接口
     * @method POST
     * @return Json
     * @throws ApiException
     */
    public function telTokenLogin()
    {
        $tel = input('tel/s', '');
        $tel = (new Aes())->decryptWithOpenssl($tel, 'zyhsapp');
        $loginToken = input('login_token/s', '');
        $areaCode = input('area_code/d', 86);
        $time = $this->request->time();
        $appConfig = config('zyhsapp');

        //准币测试号
        if (isset($appConfig['coin_mobile'][$tel]) && $appConfig['coin_mobile'][$tel] === 2)
        {
            return show(config('code.error'), '该账号禁止登录');
        }

        $mobileTel = $areaCode === 86 ? $tel : $areaCode . '-' . $tel;
        $loginTokenCache = CacheZyhs::get('bindTel:loginToken:' . $mobileTel, '');
        if (empty($loginToken) || $loginToken !== $loginTokenCache)
        {
            return show(405, '登录失败');
        }

        // 手机号不可注册
        $user = $this->CheckUserTel($tel, $areaCode);
        if (!$user)
        {
            return show(405, '登录失败');
        }
        // 生成token  和 token到期时间
        $token = IAuth::setAppLoginToken($tel);
        $data = [
            'token' => $token,
            'token_expire' => strtotime("+" . $appConfig['login_time_out_day'] . " days"),
        ];
        $UserModel = new ZyhsUser();
        //判断用户是否绑定准了号
        $UserModel->check_uen($user);
        $nickname = preg_replace('/^([\w-]{3})([\w]*)([0-9]{4}$)/i', '$1****$3', $tel);;
        // 该用户是否正常  forbidden==1 禁止登录
        if ($user['forbidden'] == 0)
        {
            // 已过期重新生成access_token
            if ($time > $user['token_expire'] || !in_array($tel, $appConfig['mobile']))
            {
                $mobileTel = $areaCode === 86 ? $tel : $areaCode . '-' . $tel;
                $UserModel->save($data, ['tel' => $mobileTel]);
            } else
            {
                $token = $user['token'];
            }
            if (!$user['nickname'])
            {
                try
                {
                    $UserModel->where('tel', $tel)->update(['nickname' => $nickname]);
                }
                catch (\Exception $e)
                {
                    Log::write('手机验证码登陆时初始化用户昵称失败' . $e->getMessage(), true);
                }
            }
        } elseif ($user['forbidden'] == 1)
        {
            return show(config('code.error'), '该账号禁止登录');
        }

        $id = (int)($user['id']);
        // 获取自己档案ID
        $recordInfo = (new ZyhsRecode())->getRecodeLists($id, 1);
        $result = [
            'id' => $id,
            'self_rid' => $recordInfo ? (int)($recordInfo['id'] ?? 0) : 0,
            'user_access_token' => (new Aes())->encryptWithOpenssl($token . "||" . $user['id'], 'zyhsapp'),
            'has_bind_tel' => 1,     // 是否绑定了手机号 1绑定了 0未绑定
            'uen' => $user['uen'],
            'is_register' => 0,
            'tel' => $tel,
        ];
        // 记录登陆日志
        $this->LoginLog($id, 4);
        $UserModel->removeUserCache($id);
        CacheZyhs::rm('bindTel:loginToken:' . $mobileTel);
        return show(config('code.success'), 'ok', $result);
    }
}
